/*
 * @lc app=leetcode.cn id=547 lang=java
 *
 * [547] 省份数量
 */

// @lc code=start
class Solution {
    public int findCircleNum(int[][] isConnected) {
        // 解法1：dfs
        boolean[] visited = new boolean[isConnected.length];
        int count = 0;
        for (int i = 0; i < isConnected.length; i++) {
            if (visited[i])
                continue;
            dfs(isConnected, visited, i);
            count++;
        }
        return count;

        // // 方法 2：bfs
        // int[] visited = new int[isConnected.length];
        // int count = 0;
        // Queue < Integer > queue = new LinkedList < > ();
        // for (int i = 0; i < isConnected.length; i++) {
        //     if (visited[i] == 0) {
        //         queue.add(i);
        //         while (!queue.isEmpty()) {
        //             int s = queue.remove();
        //             visited[s] = 1;
        //             for (int j = 0; j < isConnected.length; j++) {
        //                 if (isConnected[s][j] == 1 && visited[j] == 0)
        //                     queue.add(j);
        //             }
        //         }
        //         count++;
        //     }
        // }
        // return count;

        // // 解法3：并查集
        // int n = M.length;
        // UF uf = new UF(n);
        // for (int i = 0; i < n; i++) {
        //     for (int j = 0; j < i; j++) {
        //         if (M[i][j] == 1)
        //             uf.union(i, j);
        //     }
        // }
        // return uf.count();
    }

    public void dfs(int[][] isConnected, boolean[] visited, int i) {
        for (int j = 0; j < isConnected.length; j++) {
            if (isConnected[i][j] == 0 || visited[j])
                continue;
            visited[j] = true;
            dfs(isConnected, visited, j);
        }
    }

}

class UF {
    // 连通分量个数
    private int count;
    // 存储一棵树
    private int[] parent;
    // 记录树的“重量”
    private int[] size;

    public UF(int n) {
        this.count = n;
        parent = new int[n];
        size = new int[n];
        for (int i = 0; i < n; i++) {
            parent[i] = i;
            size[i] = 1;
        }
    }

    public void union(int p, int q) {
        int rootP = find(p);
        int rootQ = find(q);
        if (rootP == rootQ)
            return;

        // 小树接到大树下面，较平衡
        if (size[rootP] > size[rootQ]) {
            parent[rootQ] = rootP;
            size[rootP] += size[rootQ];
        } else {
            parent[rootP] = rootQ;
            size[rootQ] += size[rootP];
        }
        count--;
    }

    public boolean connected(int p, int q) {
        int rootP = find(p);
        int rootQ = find(q);
        return rootP == rootQ;
    }

    private int find(int x) {
        while (parent[x] != x) {
            // 进行路径压缩
            parent[x] = parent[parent[x]];
            x = parent[x];
        }
        return x;
    }

    public int count() {
        return count;
    }
}
// @lc code=end

